﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using MasterDetailTemplate.Models;
using Newtonsoft.Json;

namespace MasterDetailTemplate.Services.impl
{
    public class SplitSentenceService : ISplitSentenceService {
        // 完成url = url + param + sentence + config
        public const string url = "http://api.pullword.com/get.php?";
        public const string param = "source=";
        public const string config = "&param1=0&param2=1&json=1";

        private IAlertService _alertService;

        /// <summary>
        /// 将句子拆分为具有语义的词语
        /// </summary>
        /// <param name="sentence">待拆分句子</param>
        /// <param name="threshold">概率阈值</param>
        /// <returns></returns>
        public async Task<List<WordOdds>> SplitSentenceToWords(string sentence) {
            string urlGET = url + param + sentence + config;
            if (sentence == null || "".Equals(sentence)) {
                return null;
            }

            List<WordOdds> resultList;
            using (var httpClient = new HttpClient()) {
                HttpResponseMessage response = null;
                try {
                    response =
                        await httpClient.GetAsync(
                        urlGET);
                    response.EnsureSuccessStatusCode();

                }catch(Exception e)
                {
                    _alertService.ShowAlert(
                        ErrorMessages.HTTP_CLIENT_ERROR_TITLE,
                        ErrorMessages.HttpClientErrorMessage("分词服务器", e.Message),
                        ErrorMessages.HTTP_CLIENT_ERROR_BUTTON);
                    return null;
                }
                var json = await response.Content.ReadAsStringAsync();

                resultList =
                    JsonConvert.DeserializeObject<List<WordOdds>>(json);
            }

            return resultList;
        }

        public List<string> filtrateByThreshold(List<WordOdds> wordOddsList,double threshold) {
            List<string> wordList = new List<string>();
            foreach (var wordOdds in wordOddsList) {
                if (wordOdds.p > threshold) {
                    wordList.Add(wordOdds.t);
                }
            }
            return wordList;
        }

        public SplitSentenceService(IAlertService alertService) {
            _alertService = alertService;
        }
    }

    public class WordOdds {
        public string t { set; get; }
        public double p { set; get; }
    }
}
